package server.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import server.business.mapper.*;
import server.business.pojo.*;
import server.business.service.*;
import server.business.utils.GenerateNumberBySnowFlake;
import server.business.utils.PageResult;
import server.business.utils.Result;
import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lmj
 * @date 2022/8/8
 */
@Controller
@RequestMapping("/bloodTest")
public class BloodTestController {
    //将service注入进来
    @Autowired
    private BloodTestService bloodTestService;
    @Autowired
    private BloodTestMapper bloodTestMapper;
    @Autowired
    private BloodTestVoMapper bloodTestVoMapper;
    @Autowired
    private AboTypeMapper aboTypeMapper;
    @Autowired
    private RhTypeMapper rhTypeMapper;
    @Autowired
    private BloodTestStatesMapper bloodTestStatesMapper;
    @Autowired
    private BloodSamplePatientMapper bloodSamplePatientMapper;
    @Autowired
    private PatientService patientService;
    @Autowired
    private BloodTestReviewService bloodTestReviewService;
    @Autowired
    private BloodTestReviewMapper bloodTestReviewMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private BloodSamplePatientService bloodSamplePatientService;


    /**
     * 获取页面
     * 血液检验分页查询
     */
    @RequestMapping("/normal/listByPage")
    @ResponseBody
    public PageResult getPagBloodTest(HttpServletRequest request, HttpServletResponse response) {
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        Page<BloodTestVo> page = new Page<>(currentPage,pageSize);
        QueryWrapper<BloodTestVo> queryWrapper=new QueryWrapper<>();
        IPage<BloodTestVo> samplePage = bloodTestMapper.selectBloodTestByPage(page,queryWrapper);
        PageResult pageResult = new PageResult("200", "成功", samplePage.getRecords(), currentPage, pageSize,
                samplePage.getTotal(), samplePage.getPages());
        List<BloodTestVo> bloodTestVo=page.getRecords();
        return pageResult;
    }

    /**
     * 根据患者血样编号回填病历号和姓名
     * @param bloodTestVo
     * @return
     */
    @RequestMapping("/normal/getPatientInformation")
    @ResponseBody
    public Result returnPatientInformation(@RequestBody BloodTestVo bloodTestVo){
        Result result=new Result();
        //根据患者血样编号查找血样信息
        BloodSamplePatient bloodSamplePatient=
                bloodSamplePatientMapper.selectByNumber(bloodTestVo.getBloodSampleNumber());
        //根据id查询patient
        Patient patient=patientService.getById(bloodSamplePatient.getPatientId());
        result.setData(patient);
        return result;
    }
    /**
     * 验血信息登记
     * @return {@link Result}
     */
    @RequestMapping("/normal/add")
    @ResponseBody
    public Result addBloodTest(@RequestBody BloodTestVo bloodTestVo) {
        //自动生成验血单号
        GenerateNumberBySnowFlake generateNumberBySnowFlake=new GenerateNumberBySnowFlake(10,"YX");
        String inspectionSheet=generateNumberBySnowFlake.genNumberByflag();
        //找到对应病人设置patient_id
        Patient patient= (Patient) returnPatientInformation(bloodTestVo).getData();
        bloodTestVo.setPatientId(patient.getId());
        //根据患者血样编号找到血样
        BloodSamplePatient bloodSamplePatient=bloodSamplePatientMapper.selectByNumber(bloodTestVo.getBloodSampleNumber());
        bloodSamplePatient.setIsInvalid(1);
        bloodTestVo.setSamplePatientId(bloodSamplePatient.getId());
//        bloodTestVo.setGmtCreate(new Date());
        bloodTestVo.setState("1");
        bloodTestVo.setIsDeleted(0);
        bloodTestVo.setInspectionSheet(inspectionSheet);
        //拷贝成BloodTest
        BloodTest bloodTest=new BloodTest();
        BeanUtils.copyProperties(bloodTestVo,bloodTest);
        Result result = new Result();
        boolean success =bloodTestService.save(bloodTest);
        //修改验血血样状态（失效），不能再用了
        bloodSamplePatientService.updateById(bloodSamplePatient);
        //审核登记
        BloodTestReview bloodTestReview=new BloodTestReview();
        bloodTestReview.setBloodTestId(bloodTest.getId());
        bloodTestReview.setApplicantId(bloodTestVo.getApplicantId());
        bloodTestReview.setApplyTime(new Date());
        bloodTestReview.setState("1");
        bloodTestReviewService.save(bloodTestReview);
        if(success){
            result.setCode("200");
            result.setMsg("插入样本成功");
        }else {
            result.setCode("500");
            result.setMsg("失败");
        }
        return result;
    }
    /**
     * 验血结果登记
     * @param bloodTestVo
     * @return
     */
    @PostMapping("/normal/testResult")
    @ResponseBody
    public Result resultBloodTest(@RequestBody BloodTestVo bloodTestVo) {
        Result result = new Result();
        bloodTestVo.setState("2");

        //拷贝成BloodTest
        BloodTest bloodTest=new BloodTest();
        BeanUtils.copyProperties(bloodTestVo,bloodTest);
        //录入数据库
        boolean success = bloodTestService.updateById(bloodTest);

        if(success) {
            result.setCode("200");
            result.setMsg("录入成功");
        }else{
            result.setCode("500");
            result.setMsg("录入失败");
        }
        return result;
    }

    /**
     * 删除通过id
     */
    @RequestMapping("/normal/deleteById")
    @ResponseBody
    public Result deleteBloodTest(@RequestBody BloodTest bloodTest) {
        boolean success = bloodTestService.removeById(bloodTest.getId());
        Result result = new Result();
        if (success) {
            result.setCode("200");
            result.setMsg("删除成功");
        } else {
            result.setCode("500");
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 批量删除
     */
    @RequestMapping("/normal/batchDelete")
    @ResponseBody
    public Result batchDeleteBloodTest(@RequestBody ArrayList<Long> ids) {
        boolean success = bloodTestService.removeByIds(ids);
        Result result = new Result();
        if (success) {
            result.setCode("200");
            result.setMsg("删除成功");
        } else {
            result.setCode("500");
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 修改
     * @param bloodTestVo
     * @return
     */
    @RequestMapping("/normal/update")
    @ResponseBody
    public Result updateBloodTest(@RequestBody BloodTestVo bloodTestVo) {
        Result result = new Result();
        //拷贝成BloodTest
        BloodTest bloodTest=new BloodTest();
        BeanUtils.copyProperties(bloodTestVo,bloodTest);
        //录入数据库
        boolean success = bloodTestService.updateById(bloodTest);
        if(success) {
            result.setCode("200");
            result.setMsg("修改成功");
        }else{
            result.setCode("500");
            result.setMsg("修改失败");
        }
        return result;
    }

    /**
     * 搜索
     *
     * @param request  请求
     * @param response 响应
     * @return {@link PageResult}
     */
    @RequestMapping("/normal/search")
    @ResponseBody
    public PageResult searchBloodTest(HttpServletRequest request, HttpServletResponse response){
        //前端获取的检验单号、patientID,状态等搜索条件
        String inspectionSheet = request.getParameter("inspectionSheet");
        String medicalRecordNumber = request.getParameter("medicalRecordNumber");
        String name = request.getParameter("name");
        String bloodType = request.getParameter("bloodType");
        String rhd = request.getParameter("rhd");
        String reviewerName = request.getParameter("reviewerName");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String state = request.getParameter("state");
        String bloodSampleNumber=request.getParameter("bloodSampleNumber");
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));

        Page<BloodTestVo> page = new Page<>(currentPage, pageSize);
//        //创建查询条件
        QueryWrapper<BloodTestVo> queryWrapper = new QueryWrapper<>();
        if (inspectionSheet != "")
            queryWrapper.eq("inspection_sheet", inspectionSheet);
        if (medicalRecordNumber != ""){
            queryWrapper.eq("medical_record_number", medicalRecordNumber);
        }
        if (bloodSampleNumber != "")
            queryWrapper.eq("blood_sample_number", bloodSampleNumber);
        if (name != "")
            queryWrapper.like("name", name);
        if (bloodType != "")
            queryWrapper.eq("blood_type", bloodType);
        if (rhd != "")
            queryWrapper.eq("rhd", rhd);
        if (reviewerName != "")
            queryWrapper.like("reviewer_name", reviewerName);
        if(startTime != "")
            queryWrapper.ge("review_time", startTime);
        if(endTime != "")
            queryWrapper.le("review_time", endTime);
        if (state != "")
            queryWrapper.eq("state",state);
        BloodTestVo bloodTestVo=new BloodTestVo();
        //查询数据库
        bloodTestMapper.selectBloodTestByPage(page, queryWrapper);

        //返回的数据
        PageResult sampleDataVo = new PageResult("200", "成功", page.getRecords(), currentPage, pageSize, page.getTotal(), page.getPages());
        sampleDataVo.setCode("200");
        sampleDataVo.setMsg("搜索成功");
        sampleDataVo.setData(page.getRecords());
        System.out.println(page.getRecords());
        return sampleDataVo;
    }


    /**
     * 下载excel
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/normal/downloadExcel")
//    @ResponseBody
    public void downloadBloodTestExcel(HttpServletRequest request, HttpServletResponse response){

        //前端获取的检验单号、patientID,状态等搜索条件
        String inspectionSheet = request.getParameter("inspectionSheet");
        String medicalRecordNumber = request.getParameter("medicalRecordNumber");
        String name = request.getParameter("name");
        String bloodType = request.getParameter("bloodType");
        String rhd = request.getParameter("rhd");
        String reviewerName = request.getParameter("reviewerName");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String state = request.getParameter("state");
        String bloodSampleNumber=request.getParameter("bloodSampleNumber");

        Result result = new Result();
        try {
            String filename = "血液检验";
            String userAgent = request.getHeader("User-Agent");
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
                filename = URLEncoder.encode(filename,"UTF-8");            }else {
                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
            response.setContentType("application/json.ms-exce");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition","filename = " + filename + ".xlsx");

            Page<BloodTestVo> page = new Page<>();
//        //创建查询条件
            QueryWrapper<BloodTestVo> queryWrapper = new QueryWrapper<>();
            if (inspectionSheet != "")
                queryWrapper.eq("inspection_sheet", inspectionSheet);
            if (medicalRecordNumber != ""){
                queryWrapper.eq("medical_record_number", medicalRecordNumber);
            }
            if (bloodSampleNumber != "")
                queryWrapper.eq("blood_sample_number", bloodSampleNumber);
            if (name != "")
                queryWrapper.like("name", name);
            if (bloodType != "")
                queryWrapper.eq("blood_type", bloodType);
            if (rhd != "")
                queryWrapper.eq("rhd", rhd);
            if (reviewerName != "")
                queryWrapper.like("reviewer_name", reviewerName);
            if(startTime != "")
                queryWrapper.ge("review_time", startTime);
            if(endTime != "")
                queryWrapper.le("review_time", endTime);
            if (state != "")
                queryWrapper.eq("state",state);
            BloodTestVo bloodTestVo=new BloodTestVo();
            //查询数据库
            List<BloodTestVo> bloodTestVoList= bloodTestMapper.selectBloodTestExcel(queryWrapper);
            EasyExcel.write(response.getOutputStream(),BloodTestVo.class).sheet("sheet").doWrite(bloodTestVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
